Reverse a Number Using C++

03-11-17 Course- CPP

This program below takes an integer from a user and reverse it. This program assumes that user inputs positive integer otherwise, it won't work correctly.

Source Code to Reverse a Number


#include <iostream>
using namespace std;

int main() {
    int n, reverse = 0;
    
    cout << "Enter an integer: ";
    cin >> n;
    while(n != 0) {
        int remainder = n%10;
        reverse = reverse*10 + remainder;
        n/=10;
    }
    
    cout << "Reversed number = " << reverse;
    
    return 0;
}

Output


Enter an integer: 12345
Reversed number = 54321